let rotate src dst a =
  let (w,h) = Preprocess.get_dims src in
  let (xo, yo) = ((w-1)/2,(h-1)/2) in
  begin
    for i = 0 to w-1 do
      for j = 0 to h-1 do
	let b = Preprocess.get (i,j,src) in
	if (b != 255) then
	  let (x,y) = (i-xo,j-yo) in
	  let (xx,yy) =
	    (float_of_int(x)*.cos(a)-.float_of_int(y)*.sin(a),float_of_int(x)
	      *.sin(a)+.float_of_int(y)*.cos(a)) in
	  if (int_of_float(xx)+xo) >= 1 && (int_of_float(xx)+xo) <= w-2 &&
	    (int_of_float(yy)+yo) >= 1 && (int_of_float(yy)+yo) <= h-2 then
	    Sdlvideo.put_pixel_color dst (int_of_float(xx)+xo)
	      (int_of_float(yy)+yo) (b,b,b);
      done;
    done;
  end

let angle img =
  let (w,h) = Preprocess.get_dims img in
  let dst = Sdlvideo.create_RGB_surface_format img [] w h in
  let hist = Array.make h 0 in
  let var = Array.make 40 0. in
  let moy = ref 0. in
  let line = ref 0. in
  let angle = ref 0. in
  let variance = ref 0. in
  for ang = -20 to 19 do
    begin
      for i = 0 to h-1 do
	for j = 0 to w-1 do
	  begin
	    Sdlvideo.put_pixel_color dst i j (255,255,255);
	    hist.(i) <- 0;
	  end
	done;
      done;
      rotate img dst ((float_of_int(ang) *. 0.0174532925)/.2.);
      line := 0.;
      moy := 0.;
      for i = 0 to h-1 do
	for j = 0 to w-1 do
	  if (Preprocess.get (j,i,dst) <= 127) then
	    begin
	      hist.(i) <- hist.(i) + 1;
	    end
	done;
	moy := !moy +. float_of_int(hist.(i));
      done;
      for i = 0 to h-1 do
	line := !line +. ((float_of_int(hist.(i)) -. (!moy /. float_of_int(h)))
 *. (float_of_int(hist.(i)) -. (!moy /. float_of_int(h))));
      done;
      var.(20+ang) <- sqrt(!line/.float_of_int(w));
    end
  done;
  for i = 0 to 19 do
    if (var.(i) > !variance) then
      begin
	angle := (float_of_int(i-20))/.2.;
	variance := var.(i);
      end
  done;
  !angle
